import 'dart:convert';

import 'package:bruno/bruno.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:sph_driver/AppConfig/Config.dart';
import 'package:sph_driver/AppConfig/ShowDialog.dart';
import 'package:sph_driver/FindGoods/VehicleAllocation.dart';
import 'package:sph_driver/Order/WaybillDetails/PayTheDeposit.dart';
import 'package:sph_driver/Order/WaybillDetails/PayTheFreight.dart';
import 'package:sph_driver/http/NoLoadingPostApi.dart';

import '../AppConfig/LocalStorage.dart';
import '../AppConfig/RouteAct.dart';
import '../Main/ProtocolDisplay.dart';
import '../Order/WaybillDetails/ECargoInsurance.dart';
import '../TabBar/TabbarView.dart';
import '../http/NoLoadingGetApi.dart';
import '../http/api.dart';
import '../l10n/messages.dart';
import '../http/getapi.dart';

class PaymentOfFeesView extends StatefulWidget {
  const PaymentOfFeesView({super.key, required this.dataMap, required this.dintanceStr, required this.needPay, required this.isDriverAdd, required this.id});
  final Map dataMap;
  final String dintanceStr;
  final bool needPay;
  final bool isDriverAdd;
  final String id;
  @override
  State<PaymentOfFeesView> createState() => _PaymentOfFeesViewState();
}

class _PaymentOfFeesViewState extends State<PaymentOfFeesView> {
  bool _switchValue = true;
  String chooseDriverStr="";
  int isAgree=0;
  bool isChooseInsure=false;
  bool showMoreInsure=false;
  bool isChooseAccident=false;
  String dintanceStr="1000";
  String freight ="";
  int freightType=1;
  List insureMsgList=[];
  List insureList=[{"id":"1","title":"货运险","subtitleStart":"最高300万保障","subtitleEnd":"交通事故、火灾爆炸、暴雨都可保","rates":"0.0003",}];
  String allMoney="";
  String captainId="";
  String driverId="";
  Map chooseDriverMap={};
  Map showMap={};
  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    if(widget.dataMap['type']==0){
      freight=(widget.dataMap['freight']).toString();
    }

    if(widget.dataMap["goodsInsurance"]!=null){
      isChooseInsure=true;
      if(widget.dataMap["goodsInsurance"][0]['insurerIdCard']!=null){
      insureMsgList=[widget.dataMap["goodsInsurance"][0]['goodsAmount'],widget.dataMap["goodsInsurance"][0]['policyholderName'],widget.dataMap["goodsInsurance"][0]['insurerName'],widget.dataMap["goodsInsurance"][0]['insurerIdCard']];
      }else{
      insureMsgList=[widget.dataMap["goodsInsurance"][0]['goodsAmount'],widget.dataMap["goodsInsurance"][0]['policyholderName'],widget.dataMap["goodsInsurance"][0]['insurerName'],"--"];
      }
    }
    getUserInfo();
    // // getinsureMessage();
    if(widget.isDriverAdd){
      showMap=widget.dataMap;
      // preAddByDriver();
    }else{
      preAddByShipper();
    }

  }
  void preAddByShipper(){
    NoLoadingApiManager.postData(
      context, // 上下文对象，用于显示提示信息等
      'api/waybill/driver/waybill/preAddByShipper', // 您的API端点
      {
        "waybillId": widget.dataMap['contract']['waybillId'],
      }, // 查询参数，如果没有可以传递null
          (responseData)  {
        setState(() {
        showMap=responseData['data'];
        });
      },
    );
  }
  void preAddByDriver(){
    NoLoadingApiManager.postData(
      context, // 上下文对象，用于显示提示信息等
      'api/waybill/driver/waybill/preAddByDriver', // 您的API端点
      {
        "goodsId": widget.dataMap['id'],
      }, // 查询参数，如果没有可以传递null
          (responseData)  {
        setState(() {
          showMap=responseData['data'];
        });
      },
    );
  }
  Future<void> getUserInfo() async {
    driverId =(await UserIdManager.getUserID())!;
    NoLoadinggetApiManager.getData(
      context, // 上下文对象，用于显示提示信息等
      'api/auth/driver/user/getLoginUser', // 您的API端点
      {}, // 查询参数，如果没有可以传递null
          (responseData)  {
        setState(() {
          captainId=responseData['data']['captainId'];
        });
      },
    );

  }
  void getinsureMessage() async {
    String? token= await TokenManager.getToken();
    dio.interceptors.add(InterceptorsWrapper(
        onRequest: (options, handler) {
          options.headers["satoken"] = token;
          return handler.next(options);
        }
    ));

    dio.get<String>(MyServiceUrl.header+'api/system/dev/insurance/page?current=1&size=20')
        .then((r) {
      setState(() {
        print(r);
        Map<String, dynamic> jsonMap = json.decode(r.toString());

        // 获取code和data
        String code = jsonMap['code'].toString();
        if (code == "200") {
          setState(() {
            insureList=jsonMap['data']['records'];
          });
        } else {}
        // 打印结果
        print('Code: $code');
      });
    }).catchError((error) {
      print(error);
    });
  }
  //获取费用总额
  Future<void>  getInsureMoney() async {
    String? token = await TokenManager.getToken();
    dio.interceptors.add(InterceptorsWrapper(
        onRequest: (options, handler) {
          options.headers["satoken"] = token;
          return handler.next(options);
        }
    ));
    dio.post(
      MyServiceUrl.header + 'api/goods/goods/pay/userPayAmount',
      data: {
        "goodsId":widget.dataMap['goodsId']!=null? widget.dataMap['goodsId']:widget.dataMap['id'],
        "loadPlaceInfo":widget.dataMap['loadPlaceInfo'],
        "unloadPlaceInfo":widget.dataMap['unloadPlaceInfo'],
        "insurance":widget.dataMap['goodsInsurance'],
      },
      options: Options(
        sendTimeout: Duration(seconds: 2),
        receiveTimeout: Duration(seconds: 50),
      ),
      onSendProgress: (a, b) => print('send ${a / b}'),
      onReceiveProgress: (a, b) =>
          print('received ${a / b}'),
    )
        .then((r) {
      setState(() {
        print(r);
        Map<String, dynamic> jsonMap = json.decode(
            r.toString());
        // 获取code和data
        String code = jsonMap['code'].toString();
        if (code == "200") {
          allMoney=jsonMap['data'];
        } else {

          BrnToast.show(jsonMap['msg'], context);
        }
      });
    }).catchError((error) {
      print(error);
      ;
    });
  }
  String convertMetersToKilometers(String metersString) {
    // 解析字符串为整数
    int meters = int.parse(metersString);

    // 转换为千米
    double kilometers = meters / 1000.0;

    // 格式化并返回字符串
    return kilometers.toStringAsFixed(2); // 返回保留两位小数的字符串
  }
  //获取运输距离
  Future<void> getDistanceAction() async {

    String? token = await TokenManager.getToken();
    dio.interceptors.add(InterceptorsWrapper(
        onRequest: (options, handler) {
          options.headers["satoken"] = token;
          return handler.next(options);
        }
    ));
    dio.get<String>("https://api.map.baidu.com/directionlite/v1/driving?origin=${widget.dataMap['unloadPlaceInfo'][0]['latitude'].toString()},${widget.dataMap['unloadPlaceInfo'][0]['longitude'].toString()}&destination=${widget.dataMap['loadPlaceInfo'][0]['latitude'].toString()},${widget.dataMap['loadPlaceInfo'][0]['longitude'].toString()}&ak=Pb9qx5M4d02snVGSQaEqGVpqybA18AS8")
        .then((r) {
      setState(() {
        print(r);
        Map<String, dynamic> jsonMap = json.decode(r.toString());
        // 获取code和data
        String code = jsonMap['status'].toString();
        if (code == "0") {
          setState(() {
            List list =jsonMap['result']['routes'];
            dintanceStr = list[0]['distance'].toString();
            print("距离:$dintanceStr");
          });
        } else {
          // BrnToast.show(jsonMap['message'], context);
        }
        // 打印结果
        print('Code: $code');
      });
    }).catchError((error) {
      print(error);
    });

  }
  @override
  Widget build(BuildContext context) {
    var messages = AppLocalizations.of(context)!;
    final screenSize = MediaQuery.of(context).size;
    return Scaffold(
      backgroundColor:MyColors.backgreyColor ,
      appBar: AppBar(
        centerTitle: true,
        backgroundColor: Colors.white,
        title: Text(widget.needPay?"支付费用":"费用信息",style: TextStyle(color: Colors.black,fontSize: 16.sp,fontWeight: FontWeight.w300),),
        ),
      body:  Column(
        children: [
          Expanded(
            child: ListView(
              children: [

                Container(
                  margin: EdgeInsets.only(top: 14.h,left: 10.w,right: 10.w),
                  padding: EdgeInsets.only(top: 8.h,left: 17.w,bottom: 8.h,right:17.w ),
                  decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.all(Radius.circular(10))),
                  child: Column(
                    children: [
                      if(widget.needPay)
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Row(
                              children: [
                                Text("订金",style: TextStyle(color: MyColors.textColor,fontSize: 14.sp,fontWeight: FontWeight.w600),),
                                SizedBox(width:4.w,),
                                BrnTagCustom.buildBorderTag(
                                  tagText: widget.dataMap['depositType']==0?'退还':"不退还",
                                  textColor: MyColors.themeColor,
                                  borderColor: MyColors.themeColor,
                                  borderWidth: 1,
                                  fontSize: 9,
                                  textPadding: EdgeInsets.only(left: 4.w,right: 4.w,top:1.h,bottom: 1.h),
                                ),
                              ],
                            ),

                            Row(
                              crossAxisAlignment: CrossAxisAlignment.end,
                              children: [
                                if(widget.dataMap['deposit']!=null)
                                Text((widget.dataMap['deposit']).toString(),style: TextStyle(color: MyColors.themeColor,fontSize: 20.sp),),
                                if(widget.dataMap['deposit']==null)
                                  Text((widget.dataMap['contract']['contractInfo']['deposit']).toString(),style: TextStyle(color: MyColors.themeColor,fontSize: 20.sp),),
                                Column(
                                  children: [
                                    Text("元",style: TextStyle(color: MyColors.themeColor),),
                                    SizedBox(height: 3.h,),
                                  ],
                                ),
                                
                              ],
                            )
                          ],
                        ),
                      if(widget.needPay)
                        Container(
                          padding: EdgeInsets.only(left: 9.w,top: 5.h,bottom: 5.h),
                          // height: 26.h,
                          color: Color.fromRGBO(251, 241, 233, 1),
                          child: Row(
                            children: [
                              Icon(Icons.volume_up,color: MyColors.themeColor,size: 20,), 
                              SizedBox(width: 4.w,),
                              Text(widget.dataMap['depositType']==0? "订金支付到平台用于订货押金，货主收货后，退还给您":"订金支付到平台用于订货押金，您装货后，\n支付给货主，平台不做收取",style: TextStyle(color: MyColors.themeColor,fontSize: 10.sp),),
                            ],
                          ),
                        ),
                      if(widget.needPay)
                        Divider(height: 16.h,color: MyColors.backgreyColor,),
                     // widget.dataMap['type']==0?
                     //  Row(
                     //    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                     //    children: [
                     //      Text("运费",style: TextStyle(color: Colors.black),),
                     //      Row(
                     //        crossAxisAlignment: CrossAxisAlignment.end,
                     //        children: [
                     //          Text("¥",style: TextStyle(color: Colors.black,fontSize: 12.sp),),
                     //          Text((widget.dataMap['freight']).toStringAsFixed(2),style: TextStyle(color: Colors.black,fontSize: 20.sp),),
                     //          Text("/趟",style: TextStyle(color: Colors.black),),
                     //        ],
                     //      )
                     //
                     //    ],
                     //  ):
                     Column(
                       children: [
                         Row(
                           mainAxisAlignment: MainAxisAlignment.spaceBetween,
                           children: [
                             Text("运费",style: TextStyle(color: MyColors.textColor,fontSize: 14.sp,fontWeight: FontWeight.w600),),
                            widget.dataMap['freight']!="0.00"&&widget.dataMap['contract']==null?
                             Text(widget.dataMap['freight'].toString()+"元",style: TextStyle(color: Colors.black,fontSize: 14.sp),)
                             : double.parse(widget.dataMap['contract']['contractInfo']['freight'])>0?
                            Text(widget.dataMap['contract']['contractInfo']['freight'].toString()+"元",style: TextStyle(color: Colors.black,fontSize: 14.sp),)
                            :Container(
                              width:120.w,
                              height: 35.h,
                              child:  TextField(
                                // controller: _textEditingController,
                                decoration: InputDecoration(
                                  hintText: "输入运费金额",
                                  hintStyle:TextStyle(fontSize: 14.sp,color: MyColors.hintColor),
                                  filled: true,

                                  fillColor: MyColors.backgreyColor,
                                  border: InputBorder.none,
                                  alignLabelWithHint: true,

                                  // contentPadding: EdgeInsets.symmetric(vertical: 8.0.h),
                                ),
                                keyboardType: TextInputType.number,
                                textAlign: TextAlign.left,
                                style: TextStyle(color: Colors.black),
                                onChanged: (value) {
                                  setState(() {
                                    freight=value;

                                  });
                                },
                              ),
                            ),


                           ],
                         ),
                       
                         SizedBox(height: 4.h,),
                         Container(
                           padding: EdgeInsets.only(left: 9.w,top: 5.h,bottom: 5.h),
                           color: Color.fromRGBO(251, 241, 233, 1),
                           child: Row(
                             children: [
                               Icon(Icons.volume_up,color: MyColors.themeColor,size: 20,),
                               SizedBox(width: 4.w,),
                               Text("请如实填写您与货主协商的的运费，如产生纠纷，该金额\n将作为判责标准",style: TextStyle(color: MyColors.themeColor,fontSize: 10.sp),),
                             ],
                           ),
                         ),
                       ],
                     ),
                      if(widget.needPay)
                      Divider(height: 16.h,color: MyColors.backgreyColor,),
                      if(widget.needPay)
                      Row(
                        crossAxisAlignment: CrossAxisAlignment.end,
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text("技术服务费",style: TextStyle(color: MyColors.textColor,fontSize: 14.sp,fontWeight: FontWeight.w600),),
                         if(showMap['techServiceCharge']!=null)
                          Text((showMap['techServiceCharge']).toString()+"元",style: TextStyle(color: MyColors.textColor,fontSize: 14.sp),),
                          if(showMap['techServiceCharge']==null)
                            Text("0.00元",style: TextStyle(color: MyColors.textColor,fontSize: 14.sp),),
                      ]
                      ),
                      // if(widget.needPay)
                      // Row(
                      //   crossAxisAlignment: CrossAxisAlignment.end,
                      //   mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      //   children: [
                      //     Text("电子合约费",style: TextStyle(color: MyColors.textColor,fontSize: 14.sp,fontWeight: FontWeight.w600),),
                      //     if(widget.dataMap['elecProtocolCharge']!=null)
                      //     Text((widget.dataMap['elecProtocolCharge']).toString()+"元",style: TextStyle(color: MyColors.textColor,fontSize: 14.sp),),
                      //     if(widget.dataMap['elecProtocolCharge']==null)
                      //       Text("0.00元",style: TextStyle(color: MyColors.textColor,fontSize: 14.sp),),
                      //   ],
                      // ),
                    ],
                  ),
                ),
                Container(
                  margin: EdgeInsets.only(top: 8.h,left: 10.w,right: 10.w),
                  padding: EdgeInsets.only(top: 8.h,left: 17.w,bottom: 8.h,right:17.w ),
                  decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.all(Radius.circular(10))),
                  child: Column(
                    children: [
                      Row(
                        children: [
                          Icon(Icons.watch_later,color: MyColors.hintColor,size: 18,),
                          SizedBox(width: 8.w,),
                          if(showMap['loadDay']!=null)
                          Text(showMap['loadDay']+" "+showMap['loadTime']+"点可装",style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                        ],
                      ),
                      SizedBox(height: 10.h,),
                      Row(
                        children: [
                          Icon(Icons.place,color: MyColors.hintColor,size: 20,),
                          SizedBox(width: 8.w,),
                            Text("预估运输里程"+" ",style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                          showMap['distance']!=null?
                          Text(showMap['distance'],style: TextStyle(color: Colors.black,fontSize: 14.sp,fontWeight: FontWeight.w600),):
                          Text("--",style: TextStyle(color: Colors.black,fontSize: 14.sp,fontWeight: FontWeight.w600),),
                          Text("公里",style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                        ],
                      ),
                    ],
                      ),
                ),
                // Container(
                //   margin: EdgeInsets.only(top: 8.h,left: 10.w,right: 10.w),
                //   padding: EdgeInsets.only(top: 8.h,left: 13.w,bottom:8.h,right:18.w ),
                //   decoration: BoxDecoration(
                //       color: Colors.white,
                //       borderRadius: BorderRadius.all(Radius.circular(10))),
                //   child: Column(
                //     children: [
                //       Row(
                //         mainAxisAlignment: MainAxisAlignment.spaceBetween,
                //         children: [
                //           Row(
                //             children: [
                //         Image.asset("lib/Images/OrderList/支付费用保险icon.png",width: 21.w,height: 21.h,),
                //               Text("保险",style: TextStyle(color: MyColors.themeColor,fontSize: 14.sp)),
                //             ],
                //           ),
                //           Row(
                //             children: [
                //              if(widget.dataMap['goodsInsurance']!=null)
                //               Text(widget.dataMap['goodsInsurance'][0]['insuranceAmount']+"元",style: TextStyle(color: MyColors.themeColor,fontSize: 14.sp)),
                //              GestureDetector(
                //                child: Icon(isChooseInsure? Icons.check_circle:Icons.radio_button_off,color: isChooseInsure?MyColors.themeColor: MyColors.textColor,),
                //                 onTap: (){
                //                   setState(() {
                //                     if(widget.dataMap['goodsInsurance']==null)
                //                       isChooseInsure=!isChooseInsure;
                //                   });
                //                 },
                //                 ),
                // 
                //             ],
                //           ),
                //         ],
                //       ),
                //       if(isChooseInsure)
                //       Row(
                //         children: [
                //           Text("货运险",style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                //           SizedBox(width: 8.w,),
                //           Text("最高300万保障",style: TextStyle(color: MyColors.textColor,fontSize: 12.sp),),
                //           // GestureDetector(
                //           //   child: Text("产品介绍>",style: TextStyle(color: MyColors.textColor,fontSize: 12.sp),),
                //           //   onTap: ()async{
                //           //     final result= await Navigator.push( context, FadeRoute(page:ECargoInsurance(insureList: insureMsgList,
                //           //     )));
                //           //
                //           //     if(result!=null){
                //           //       setState(() {
                //           //         insureMsgList=result;
                //           //       });
                //           //     }
                //           //   },
                //           // )
                //         ],
                //       ),
                //       if(isChooseInsure)
                //       SizedBox(height: 6.h,),
                //       if(isChooseInsure)
                //       Container(
                //         padding: EdgeInsets.only(top: 8.h,left: 16.w,bottom: 8.h,right:6.w ),
                //         decoration: BoxDecoration(
                //             color: MyColors.backgreyColor,
                //             borderRadius: BorderRadius.all(Radius.circular(10))),
                //         child:Column(
                //           children: [
                //             Row(
                //               mainAxisAlignment: MainAxisAlignment.spaceBetween,
                //               children: [
                //                 if(insureMsgList.isNotEmpty)
                //                 Column(
                //                   crossAxisAlignment: CrossAxisAlignment.start,
                //                   children: [
                //                     Text("货物价值（保额）："+ insureMsgList[0],style: TextStyle(color: MyColors.textColor,fontSize: 12.sp),),
                //                     Text("保险支付方（投保人）：${insureMsgList[1][0]}",style: TextStyle(color: MyColors.textColor,fontSize: 12.sp),),
                //                     Text("被保人："+ insureMsgList[2][0],style: TextStyle(color: MyColors.textColor,fontSize: 12.sp),),
                //                     Text("被保人证件号码："+ insureMsgList[2][1],style: TextStyle(color: MyColors.textColor,fontSize: 12.sp),),
                //                   ],
                //                 ),
                //                 if(insureMsgList.isEmpty)
                //                   Column(
                //                     crossAxisAlignment: CrossAxisAlignment.start,
                //                     children: [
                //                       Text("货物价值（保额）：",style: TextStyle(color: MyColors.textColor,fontSize: 12.sp),),
                //                       Text("保险支付方（投保人）：",style: TextStyle(color: MyColors.textColor,fontSize: 12.sp),),
                //                       Text("被保人：",style: TextStyle(color: MyColors.textColor,fontSize: 12.sp),),
                //                       Text("被保人证件号码：",style: TextStyle(color: MyColors.textColor,fontSize: 12.sp),),
                //                     ],
                //                   ),
                //                 if(widget.dataMap['goodsInsurance']==null)
                //                 TextButton(onPressed: ()async{
                //                   final result= await Navigator.push( context, FadeRoute(page:ECargoInsurance(insureList: insureMsgList,
                //                   )));
                //                  if(result!=null){
                //                    setState(() {
                //                      insureMsgList=result;
                //                    });
                //                  }
                //                 }, child: Text("编辑",style: TextStyle(color: MyColors.themeColor,fontSize: 14.sp),))
                //               ],
                //             ),
                //           ],
                //         ) ,
                //       ),
                //       if(widget.dataMap['goodsInsurance']!=null&&widget.dataMap['goodsInsurance'].length>1&&isChooseInsure)
                //       SizedBox(height: 4.h,),
                //       if(widget.dataMap['goodsInsurance']!=null&&widget.dataMap['goodsInsurance'].length>1&&isChooseInsure)
                //       GestureDetector(
                //         child:  Row(
                //           mainAxisAlignment: MainAxisAlignment.end,
                //           children: [
                //             Text(showMoreInsure?"收起":'展开',style: TextStyle(color: Colors.black,fontSize: 12.sp),),
                //             Icon(showMoreInsure?Icons.keyboard_arrow_up :Icons.keyboard_arrow_down,color: MyColors.authTipColor,),
                //           ],
                //         ),
                //         onTap: (){
                //           setState(() {
                //             showMoreInsure =!showMoreInsure;
                //           });
                //         },
                //       ),
                //
                //
                //           ],
                //         ),
                //       ),
                Container(
                  margin: EdgeInsets.only(left: 10.w,right: 10.w),
                  color: Color.fromRGBO(239, 239, 239, 1),
                  height:showMoreInsure? 120.h :0.0,
                  child:Column(
                    children: [
                      Container(
                          padding:EdgeInsets.only(left: 11.w,top: 10.h,right: 9.w,bottom: 10.h),
                          margin: EdgeInsets.only(left: 16.w,right: 16.w,top: 8.h),
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(10),
                            color:Colors.white,
                          ),
                          child:Column(
                            children: [
                              Row(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                children: [
                                  Row(
                                    children: [
                                      Text("驾乘意外险",style: TextStyle(color: Colors.black,fontSize: 12.sp)),
                                      SizedBox(width: 8.w,),
                                      Text("XXXXXXXXXXX，可保多少万",style: TextStyle(color: MyColors.hintColor,fontSize: 10.sp),),
                                    ],
                                  ),

                                  GestureDetector(
                                    child: isChooseAccident? Icon(Icons.check_circle,color: MyColors.themeColor,size: 20,):Icon(Icons.radio_button_off,color: MyColors.textColor,size: 20,),
                                    onTap: (){
                                        setState(() {
                                          isChooseAccident=!isChooseAccident;
                                        });
                                    },
                                  ),
                                ],
                              ),
                              SizedBox(height: 8.h,),
                              Container(
                                color: Color.fromRGBO(248, 248, 248, 1),
                                height: 45.h,
                                child: Center(child: Text("+添加被保人",style: TextStyle(color: MyColors.textColor),),),
                              ),
                            ],
                          )

                      ),
                    ],
                  ),
                ),
                // Container(
                //   margin: EdgeInsets.only(top: 8.h,left: 10.w,right: 10.w),
                //   padding: EdgeInsets.only(top: 11.h,left: 17.w,bottom: 11.h,right:11.w ),
                //   decoration: BoxDecoration(
                //       color: Colors.white,
                //       borderRadius: BorderRadius.all(Radius.circular(10))),
                //   child: Row(
                //     mainAxisAlignment: MainAxisAlignment.spaceBetween,
                //     children: [
                //       Text("优惠券抵扣",style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                //       Row(
                //         children: [
                //           Container(
                //             color:Color.fromRGBO(251, 231, 189, 1) ,
                //             child: Row(
                //             children: [
                //               Image.asset("lib/Images/OrderList/支付费用优惠icon.png",width: 14.w,height: 14.h,),
                //               Text("技术服务费",style: TextStyle(color: Color.fromRGBO(195, 136, 53, 1),fontSize: 10.sp),),
                //             ],
                //             ),
                //
                //           ),
                //           Text("-¥"+"3.00",style: TextStyle(color: MyColors.themeColor,fontSize: 14.sp),),
                //           Icon(Icons.arrow_forward_ios,size: 20,color: MyColors.hintColor,),
                //         ],
                //       )
                //     ],
                //   ),
                // ),
                Container(
                  margin: EdgeInsets.only(top: 8.h,left: 10.w,right: 10.w),
                  padding: EdgeInsets.only(top:8.h,left: 17.w,bottom: 8.h,right:15.w ),
                  decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.all(Radius.circular(10))),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text("授权货主取ETC发票",style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                          Container(
                            height: 15.h,
                            child:  Switch(
                              value: _switchValue,
                              onChanged: (value) {
                                setState(() {
                                  _switchValue = value;
                                });
                              },
                              activeColor: Colors.white,
                              inactiveTrackColor: MyColors.backgreyColor,
                              activeTrackColor: MyColors.themeColor,
                            ),
                          ),
                        
                        ],
                      ),
                      SizedBox(height: 4.h,),
                      Text("本人承诺在速配货平台成交所有订单归平台所有",style: TextStyle(fontSize: 12.sp,color: MyColors.hintColor),)
                    ],
                  ),
              ),
                SizedBox(height: 8.h,),
                Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    IconButton(onPressed: (){
                      setState(() {
                        isAgree==0?isAgree=1:isAgree=0;
                      });
                    }, icon: Icon(isAgree==0? Icons.panorama_fisheye:Icons.radio_button_on,color:isAgree==0?MyColors.textColor:MyColors.themeColor ,size: 20,)),
                    Container(
                        width: 300.w,
                      child:  RichText(
                        text: TextSpan(children: [
                          TextSpan(
                              text: "确认支付即视为您已阅读并同意 ",
                              style: TextStyle(fontSize: 12.sp, decoration: TextDecoration.none,color: Colors.black54,)),
                          TextSpan(
                              text: '《货物运输协议》',
                              style: TextStyle(fontSize: 12.sp,decoration: TextDecoration.none, color: MyColors.blueColor),
                              recognizer: TapGestureRecognizer()
                                ..onTap = () {
                                  Navigator.push( context, FadeRoute(page:ProtocolDisplay(id: "1805851815423774721",)));
                                }),
                          TextSpan(
                              text: '《速配货平台订金担保规则》',

                              style: TextStyle(fontSize: 12.sp,decoration: TextDecoration.none, color: MyColors.blueColor),
                              recognizer: TapGestureRecognizer()
                                ..onTap = () {
                                  Navigator.push( context, FadeRoute(page:ProtocolDisplay(id: "1805853468734525442",)));
                                }),
                          TextSpan(
                              text: '《技术服务协议》',

                              style: TextStyle(fontSize: 12.sp,decoration: TextDecoration.none, color: MyColors.blueColor),
                              recognizer: TapGestureRecognizer()
                                ..onTap = () {
                                  Navigator.push( context, FadeRoute(page:ProtocolDisplay(id: "1805852208060960770",)));
                                }),
                          // TextSpan(
                          //     text: '《委托代开增值税发票协议》',
                          //
                          //     style: TextStyle(fontSize: 12.sp,decoration: TextDecoration.none, color: MyColors.blueColor),
                          //     recognizer: TapGestureRecognizer()
                          //       ..onTap = () {
                          //         // 查看 服务条款
                          //       }),
                          TextSpan(
                              text: '《ETC取票规则》',

                              style: TextStyle(fontSize: 12.sp,decoration: TextDecoration.none, color: MyColors.blueColor),
                              recognizer: TapGestureRecognizer()
                                ..onTap = () {
                                  Navigator.push( context, FadeRoute(page:ProtocolDisplay(id: "1805855371287597058",)));
                                }),
                          TextSpan(
                              text: "所有内容 ",
                              style: TextStyle(fontSize: 12.sp, decoration: TextDecoration.none,color: Colors.black54,)),
                        ]),
                      ),
                    )
                  ],
                )
              ],
          ),
          ),
          Container(
            padding: EdgeInsets.only(left: 16.w,right: 18.w,top: 8.h,bottom: 44.h),
            decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.all(Radius.circular(10))),
            child: Column(
              children: [
                if(driverId==captainId&&widget.isDriverAdd==true)
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Row(
                      children: [
                        Text("分配车辆",style: TextStyle(color: Colors.black,fontSize: 14.sp,fontWeight: FontWeight.w600),),
                        SizedBox(width: 4.w,),
                        GestureDetector(
                          child: Icon(Icons.help_outline,color: MyColors.hintColor,size: 20,),
                          onTap: (){
                            showTooltip(context, '使用分配订单信息同步，\n运输更省心！');
                          },
                        ),
                      ],
                    ),
                    GestureDetector(
                      child: Text(chooseDriverStr==""?"去选择承运车辆，轨迹实时同步>":chooseDriverStr,style: TextStyle(color: MyColors.themeColor),),
                      onTap: ()async {
                       final result=await  Navigator.push( context, FadeRoute(page:VehicleAllocation(category: widget.dataMap['category'],

                       )));

                       if (result!=null){
                        setState(() {
                          chooseDriverMap=result;
                          chooseDriverStr=result['realName']+"  "+result['vehicleNum'];
                        });

                       }
                      },
                    ),
                  ],
                ),
                SizedBox(height: 13.h,),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    if((widget.dataMap['deposit']!=null&&widget.dataMap['deposit']=="0.00")||(widget.dataMap['deposit']==null&&widget.dataMap['contract']['contractInfo']['deposit']=="0.00"))
                        SizedBox(),
                      if((widget.dataMap['deposit']!=null&&widget.dataMap['deposit']!="0.00")||(widget.dataMap['deposit']==null&&widget.dataMap['contract']['contractInfo']['deposit']!="0.00"))
                    Column(
                      children: [
                        Row(
                          crossAxisAlignment: CrossAxisAlignment.end,
                          children: [
                           if(widget.dataMap['deposit']!=null)
                            Text(widget.dataMap['deposit'],style: TextStyle(color: MyColors.themeColor,fontSize: 20.sp),),
                            if(widget.dataMap['deposit']==null)
                              Text(widget.dataMap['contract']['contractInfo']['deposit'],style: TextStyle(color: MyColors.themeColor,fontSize: 20.sp),),
                            SizedBox(width: 8.w,),
                            Column(
                              children: [
                                Text("元",style: TextStyle(color: MyColors.themeColor,fontSize: 12.sp),),
                                SizedBox(height: 3.w,),
                              ],
                            ),
                          
                            SizedBox(width: 8.w,),
                            GestureDetector(
                              child: Row(
                                children: [
                                  Text("详情",style: TextStyle(color: MyColors.textColor,fontSize: 12.sp),),
                                  Icon(Icons.keyboard_arrow_up,size: 15,color: MyColors.textColor,),
                                ],
                              ),
                              onTap: (){
                                showModalBottomSheet(context: context, builder: (BuildContext context)
                                {
                                  return Container(
                                    height: 300.h,
                                    padding: EdgeInsets.only(
                                        left: 20.w, top: 15.h, right: 20.w, bottom: 40.h),
                                    decoration: BoxDecoration(
                                        color: Colors.white,
                                        borderRadius: BorderRadius.all(Radius.circular(10))),
                                    child: Column(
                                      children: [
                                        Row(
                                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                          children: [
                                            SizedBox(width: 20.w,),
                                            Text("费用详情",style: TextStyle(color: Colors.black,fontSize: 16.sp),),
                                            GestureDetector(
                                              child: Icon(Icons.close,color: MyColors.textColor,size: 30,),
                                              onTap: (){
                                                Navigator.pop(context);
                                              },
                                            )
                                          ],
                                        ),
                                        SizedBox(height: 17.h,),
                                        // Row(
                                        //   mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                        //   children: [
                                        //     Text("运费",style: TextStyle(color: Colors.black,fontWeight: FontWeight.w600,fontSize: 14.sp),),
                                        //     Text(widget.dataMap['freight']==0? "电议":(widget.dataMap['freight']).toString(),style: TextStyle(color: MyColors.themeColor,fontWeight: FontWeight.w600,fontSize: 14.sp),),
                                        //   ],
                                        // ),
                                        Divider(height: 16.h,color: MyColors.backgreyColor,),
                                        Row(
                                          mainAxisAlignment: MainAxisAlignment.start,
                                          children: [
                                            Text("优惠详情",style: TextStyle(color: Colors.black,fontWeight: FontWeight.w600,fontSize: 14.sp),),
                                          ],
                                        ),

                                        SizedBox(height: 16.h,),
                                        if(widget.dataMap['deposit']!=0)
                                          Row(
                                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                            children: [
                                              Text("订金",style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                                              Row(
                                                children: [
                                                  Text((widget.dataMap['deposit']).toString(),style: TextStyle(color: Colors.black,fontWeight: FontWeight.w600,fontSize: 14.sp),),
                                                  widget.dataMap['depositType'].toString()!="0"?  Text("（退还）",style: TextStyle(color: Colors.black,fontSize: 14.sp),)
                                                      :Text("(不退还)",style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                                                ],
                                              ),

                                            ],
                                          ),
                                        SizedBox(height: 16.h,),
                                        Row(
                                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                          children: [
                                            Text("技术服务费",style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                                            Row(
                                              children: [
                                                Text(widget.dataMap['techServiceCharge'].toString()+"元",style: TextStyle(color: Colors.black,fontSize: 14.sp,),),
                                                // Text(" 优惠后3元",style: TextStyle(color: Colors.black,fontWeight: FontWeight.w600),),

                                              ],
                                            ),
                                          ],
                                        ),
                                        SizedBox(height: 10.h,),
                                        // Container(
                                        //   height:34.h,
                                        //
                                        //   decoration: BoxDecoration(
                                        //       color: Color.fromRGBO(251, 241, 233, 1),
                                        //       borderRadius: BorderRadius.all(Radius.circular(5))),
                                        //   child: Row(
                                        //     children: [
                                        //       SizedBox(width: 11.w,),
                                        //       Image.asset("lib/Images/OrderList/限时优惠icon.png",width:37.w ,height: 15.h,),
                                        //       SizedBox(width: 9.w,),
                                        //       Text("优惠"+"3"+"元",style: TextStyle(color: Colors.black),),
                                        //     ],
                                        //   ),
                                        // ),

                                      ],
                                    ),
                                  );
                                });
                              },
                            ),

                          ],
                        ),
                        Row(
                          children: [
                            Text("需要支付",style: TextStyle(color: MyColors.textColor,fontSize: 10.sp),),
                            SizedBox(width: 8.w,),
                            Text("共计优惠0元",style: TextStyle(color: MyColors.themeColor,fontSize: 10.sp),),
                          ],
                        ),
                      ],
                    ),

                    Container(
                      height: 35.h,
                      child:  BrnSmallMainButton(
                        title:showMap['needPay']!=null&&showMap['needPay']? '去支付':"立即抢单",
                        fontSize: 16.sp,
                        textColor: Colors.white,
                        bgColor: MyColors.themeColor,
                        width: 120.w,
                        radius: 30,
                        onTap: () async {
                          if(isAgree==0){
                            BrnToast.show("请阅读并同意协议信息", context, duration: BrnDuration.short,);
                          }else {

                            if(!showMap['needPay']) {
                              if(widget.isDriverAdd){
                                if (chooseDriverMap.isNotEmpty) {
                                  ApiManager.postData(
                                    context,
                                    'api/waybill/driver/waybill/addByCaptain',
                                    {
                                      "goodsId": widget.id,
                                      "freight": freight,
                                      "driverId": chooseDriverMap['driverId'],
                                      "vehicleId":chooseDriverMap['vehicleId'],
                                      "authEtc":_switchValue?1:0,
                                    },
                                        (responseData)  {
                                      BrnToast.show("提交成功", context);
                                      Navigator.pushReplacement(
                                        context,
                                        MaterialPageRoute(builder: (context) => TabbarView(pateIndex: 2,),fullscreenDialog: true,),
                                      );
                                    },
                                  );
                                } else {

                                  ApiManager.postData(
                                    context,
                                    'api/waybill/driver/waybill/addByDriver',
                                    {
                                      "goodsId": widget.id,
                                      "freight": freight,
                                      "authEtc":_switchValue?1:0,
                                    },
                                        (responseData)  {
                                      BrnToast.show("提交成功", context);
                                      Navigator.pop(context);
                                      Navigator.pop(context,"success");
                                    },
                                  );
                                }

                              }else{
                                getApiManager.getData(
                                  context, // 上下文对象，用于显示提示信息等
                                  'api/waybill/contract/agree', // 您的API端点
                                  {"id":widget.dataMap['contract']['id']}, // 查询参数，如果没有可以传递null
                                      (responseData)  {
                                    BrnToast.show(
                                      "操作成功",
                                      context,
                                      duration: BrnDuration.short,
                                    );
                                    Navigator.pushReplacement(
                                      context,
                                      MaterialPageRoute(builder: (context) => TabbarView(pateIndex: 2,),fullscreenDialog: true,),
                                    );

                                  },
                                );
                              }


                            }else{

                            if(widget.isDriverAdd){

                              NoLoadingApiManager.postData(
                                context,
                                'api/pay/wallet/driver/addDepositBillByDriver',
                                {
                                  "productId":widget.id,
                                },
                                    (responseData)  {
                                  Navigator.push( context, FadeRoute(page:PayTheDeposit(dataMap: {
                                    "serialNum":responseData['data'],
                                    "authEtc":_switchValue?1:0,
                                    "payTotal":showMap['deposit'],
                                    "isCaptain":chooseDriverMap.isNotEmpty?1:0,
                                    "vehicleId":chooseDriverMap.isNotEmpty?chooseDriverMap['vehicleId']:"",
                                    "goodsId":widget.id,
                                    "isDriverAdd":true,
                                  },
                                  )));
                                },
                              );
                            }else{

                              NoLoadingApiManager.postData(
                                context,
                                'api/pay/wallet/driver/addDepositBillByShipper',
                                {
                                  "productId":widget.id,
                                },
                                    (responseData)  {
                                  Navigator.push( context, FadeRoute(page:PayTheDeposit(dataMap: {
                                    "serialNum":responseData['data'],
                                    "authEtc":_switchValue?1:0,
                                    "payTotal": showMap['deposit'],
                                    "isCaptain":chooseDriverMap.isNotEmpty?1:0,
                                    "vehicleId":chooseDriverMap.isNotEmpty?chooseDriverMap['vehicleId']:"",
                                    "goodsId":widget.id,
                                    "isDriverAdd":false,
                                    "waybillId":widget.id,
                                  },
                                  )));
                                },
                              );
                            }


                            }
                          }
                        },
                      ),
                    ),
                    // if(widget.dataMap['deposit']==null)
                    //   Container(
                    //     height: 35.h,
                    //     child:  BrnSmallMainButton(
                    //         title: widget.needPay? '去支付':"确认协议",
                    //         fontSize: 16.sp,
                    //         textColor: Colors.white,
                    //         bgColor: MyColors.themeColor,
                    //         width: 120.w,
                    //         radius: 30,
                    //         onTap: () async {
                    //           if(isAgree==0){
                    //             BrnToast.show("请阅读并同意协议信息", context, duration: BrnDuration.short,);
                    //           }else {
                    //           if(widget.needPay){
                    //             NoLoadingApiManager.postData(
                    //               context,
                    //               'api/pay/wallet/driver/addDepositBillByDriver',
                    //               {
                    //                 "productId":widget.dataMap['id'],
                    //               },
                    //                   (responseData)  {
                    //                 Navigator.push( context, FadeRoute(page:PayTheDeposit(dataMap: {
                    //                   "serialNum":responseData['data'],
                    //                   "authEtc":_switchValue?1:0,
                    //                   "payTotal": widget.dataMap['contract']['contractInfo']['deposit'],
                    //                   "isCaptain":chooseDriverMap.isNotEmpty?1:0,
                    //                   "vehicleId":chooseDriverMap.isNotEmpty?chooseDriverMap['vehicleId']:"",
                    //                 },
                    //                 )));
                    //               },
                    //             );
                    //           }else{
                    //             getApiManager.getData(
                    //               context, // 上下文对象，用于显示提示信息等
                    //               'api/waybill/contract/agree', // 您的API端点
                    //               {"id":widget.dataMap['contract']['id']}, // 查询参数，如果没有可以传递null
                    //                   (responseData)  {
                    //                 BrnToast.show(
                    //                   "操作成功",
                    //                   context,
                    //                   duration: BrnDuration.short,
                    //                 );
                    //                 Navigator.pushReplacement(
                    //                   context,
                    //                   MaterialPageRoute(builder: (context) => TabbarView(pateIndex: 2,),fullscreenDialog: true,),
                    //                 );
                    //
                    //               },
                    //             );
                    //           }
                    //           }
                    //         }
                    //     ),
                    //   ),

                  ],
                ),
              ],
    ),

          ),
        ],
      ),
    );
  }
  void showTooltip(BuildContext context, String message) {
    final RenderBox renderBox = context.findRenderObject() as RenderBox;
    final Offset offset = renderBox.localToGlobal(Offset.zero);

    // 调整margin的值
    double topMargin = offset.dy - 40;
    double leftMargin = offset.dx;
    topMargin = topMargin < 0 ? 0 : topMargin;
    leftMargin = leftMargin < 0 ? 0 : leftMargin;

    // 在底部高度为130的位置加上一个固定值
    topMargin +=  MediaQuery.of(context).size.height-210;
    // 使用showGeneralDialog显示tooltip
    showGeneralDialog(
      context: context,
      barrierColor: Colors.transparent,
      barrierDismissible: true,
      barrierLabel: '',
      transitionDuration: Duration(milliseconds: 200),
      pageBuilder: (context, animation1, animation2) {
        return Align(
          alignment: Alignment.topLeft,
          child: Container(
            margin: EdgeInsets.only(top: topMargin, left: leftMargin),
            child: Material(
              color: Colors.transparent,
              child: Container(
                padding: EdgeInsets.all(10),
                decoration: BoxDecoration(
                  color: Colors.black,
                  borderRadius: BorderRadius.circular(8),
                ),
                child: Text(
                  message,
                  style: TextStyle(color: Colors.white),
                ),
              ),
            ),
          ),
        );
      },
    );
  }

}
